package com.ccx.coachsite.weibo;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.util.SUtil;
import com.ccx.coachsite.weibo.auth2.WeiBoContants;
import com.ccx.coachsite.weibo.auth2.WeiBoDBUtil;
import com.ccx.coachsite.weibo.auth2.net.Weibo;
import com.ccx.coachsite.weibo.auth2.net.WeiboException;
import com.ccx.coachsite.weibo.auth2.vo.LoginUser;



/**
 * 微博授权的登录窗口
 * zhuchenghua
 */
public class WeiBoLoginActivity extends Activity implements OnClickListener{
	
	private Context mContext;
	
	private ImageView im_close;
	private Button btn_login;
	private EditText et_username;
	private EditText et_password;
	private Button btn_regist;
	private CheckBox cb_attend_pandahome;
	
	private final int EVENT_AUTH_END=1000;
	private boolean mAuthResult=false;
	/**正在登录*/
	private boolean mIsRequesting=false;
	
	private Weibo mWeibo;
	
	private ProgressDialog pd;
	private Thread mThrAuth;
	
	/**网络异常的全局Handler事件 */
	public final static int EVENT_CONNECTION_FAILED=-11111;//网络异常
	
	/**全局Handler事件--未知错误*/
	public final static int EVENT_ERROR=-11112;
	
	private Handler mEventHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			switch(msg.what)
			{
			//授权结束
			case EVENT_AUTH_END:
				if(mAuthResult==true)//授权成功
				{
					talk(getString(R.string.weibo_auth_success));
					Intent intent=new Intent();
					intent.putExtra(WeiBoContants.Login.EXTRA_WEIBO_LOGIN_RESULT, true);
					setResult(WeiBoContants.Login.RESULT_CODE_WEIBO_LOGIN, intent);
					finish();
				}
				else
					talk(getString(R.string.weibo_auth_failed));
				break;
			case EVENT_CONNECTION_FAILED:
				talk(getString(R.string.hit_network_problem));
				break;
			case EVENT_ERROR:
				Bundle bundle=msg.getData();
				String error=(String) bundle.get("error");
				talk(error);
				break;
			}
			
			if(pd!=null)
				pd.dismiss();
			mIsRequesting=false;
		}
		
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weibo_login_show);
        im_close=(ImageView) findViewById(R.id.im_close);
		btn_login=(Button) findViewById(R.id.btn_login);
		et_username=(EditText) findViewById(R.id.et_username);
		et_password=(EditText) findViewById(R.id.et_password);
		btn_regist=(Button) findViewById(R.id.btn_regist);
		cb_attend_pandahome=(CheckBox)findViewById(R.id.cb_attend_pandahome);
		
		im_close.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		btn_regist.setOnClickListener(this);
		mWeibo=Weibo.getInstance(this);
		mContext=this;
		
    }
	@Override
	public void onClick(View v) {
		switch(v.getId())
		{
		case R.id.im_close:
			finish();
			break;
		case R.id.btn_login:
			beginAuth();
			break;
		//注册
		case R.id.btn_regist:
			Intent intent=new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("http://weibo.cn/dpool/ttt/h5/reg.php?wm=0&act=mail"));
			startActivity(intent);
			/*Intent intent=new Intent(this,WeiboRegisteActivity.class);
			startActivityForResult(intent, WeiBoContants.Register.REQUEST_CODE_WEIBO_REGIST);*/
			break;
		}
	}
	/**
	 * 开始授权
	 */
	private void beginAuth()
	{
		if(mIsRequesting)
			return;
		final String mUserName=et_username.getText().toString();
		final String mPassword=et_password.getText().toString();
		//是否关注91桌面
		final boolean mAttended=cb_attend_pandahome.isChecked();
		
		//用户名密码不能为空
		if(SUtil.isEmpty(mUserName)||SUtil.isEmpty(mPassword))
		{
			talk(getString(R.string.weibo_auth_required));
			return;
		}
		
		pd=new ProgressDialog(this);
		pd.setMessage(getString(R.string.weibo_auth_perform));
		pd.show();
		mIsRequesting=true;
		mThrAuth=new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					//登录
					LoginUser loginUser=mWeibo.doLogin(mUserName, mPassword);
					
					//保存登陆信息
					WeiBoDBUtil.addLoginUser(mContext, loginUser);
					
					//关注91桌面
					if(mAttended){
						//熊猫桌面的微博昵称"91桌面"
						String weibo_Pandahome=getString(R.string.weibo_pandahome);
						try {
							mWeibo.addFriend(null, weibo_Pandahome, loginUser.getAccessToke());
						} catch (Exception e) {
							Log.d("WeiBoLoginActivity", "");
						}
					}
						
					mAuthResult=true;
					sendMessage(EVENT_AUTH_END);
				} catch (Exception e) {
					if((e instanceof MalformedURLException)||(e instanceof IOException)||(e instanceof SocketTimeoutException)) //网络异常
						mEventHandler.sendEmptyMessage(EVENT_CONNECTION_FAILED);
					else{
						int errorCode=-1;
						if(e instanceof WeiboException)
							errorCode=((WeiboException)e).getStatusCode();
						Log.w("WeiBoLoginActivity", "Weibo login failed!"+e.toString());
						Message msg=assessErrorMsg(errorCode,EVENT_ERROR);
						mEventHandler.sendMessage(msg);//登录失败
					}
					e.printStackTrace();
				}
				
			}
		});
		
		mThrAuth.start();
		
	}
	
	/**
	 * 封装Message
	 * @param errorCode
	 * @param what
	 * @return
	 */
	private Message assessErrorMsg(int errorCode,int what)
	{
		Message msg=new Message();
		msg.what=what;
		String error=WeiBoContants.getCause(errorCode);
		error=TextUtils.isEmpty(error)?getString(R.string.weibo_auth_failed):error;
		Bundle bunle=new Bundle();
		bunle.putString("error", error);
		msg.setData(bunle);
		return msg;
	}
	
	
	private void sendMessage(int what)
	{
		Message msg=new Message();
		msg.what=what;
		mEventHandler.sendMessage(msg);
	}
	private void talk(String tip)
	{
		Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
	}
	
	@Override
	protected void onDestroy() {
		if(mThrAuth!=null)
		{
			while(mThrAuth.isAlive())
			{
				mThrAuth.interrupt();
			}
		}
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		//微博注册返回
		if(requestCode==WeiBoContants.Register.REQUEST_CODE_WEIBO_REGIST&&
				resultCode==WeiBoContants.Register.RESULT_CODE_WEIBO_REGIST)
		{
			if(data!=null)
			{
				LoginUser user=(LoginUser) data.getSerializableExtra(WeiBoContants.EXTRA_USER);
				if(user!=null)
				{
					mAuthResult=true;
					sendMessage(EVENT_AUTH_END);
				}//end if
			}//end if
		}
	}
	
	

}























